{% extends "pc/template.html" %}

{% block title %}
公告列表
{% endblock %}

{% include 'pc/公共样式配置/CSS总样式.html' %}

{% block css %}
<link rel="stylesheet" href="/static/HubUI/css/sweetalert2.css">
<style>
    .container-xxl {
        padding: 2rem 1.5rem;
    }
    
    .card {
        margin: 1rem 0;
        border: none;
        border-radius: 1rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        transition: all 0.3s ease;
    }
    
    .card:hover {
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
    }
    
    .card-header {
        background: #fff;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
        border-radius: 1rem 1rem 0 0 !important;
    }
    
    .card-header h5 {
        color: #566a7f;
        font-weight: 600;
        margin: 0;
    }
    
    .btn-primary {
        background: #696cff;
        border-color: #696cff;
        padding: 0.5rem 1rem;
        font-weight: 500;
        transition: all 0.2s ease;
    }
    
    .btn-primary:hover {
        background: #5f61e6;
        border-color: #5f61e6;
        transform: translateY(-1px);
    }
    
    .table-responsive {
        margin: 0;
        padding: 1rem;
    }
    
    .table {
        margin: 0;
    }
    
    .table thead th {
        background: #f8f9fa;
        color: #566a7f;
        font-weight: 600;
        border-bottom: 2px solid #e9ecef;
        padding: 1rem;
    }
    
    .table tbody td {
        padding: 1rem;
        vertical-align: middle;
        color: #697a8d;
        border-bottom: 1px solid #e9ecef;
    }
    
    .table tbody tr {
        transition: all 0.2s ease;
    }
    
    .table tbody tr:hover {
        background: #f8f9fa;
    }
    
    .notice-content {
        max-width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    .action-buttons .btn {
        padding: 0.4rem 0.6rem;
        margin: 0 0.2rem;
        border-radius: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .action-buttons .btn:hover {
        transform: translateY(-2px);
    }
    
    .btn-info {
        background: #03c3ec;
        border-color: #03c3ec;
        color: #fff;
    }
    
    .btn-info:hover {
        background: #02a8c8;
        border-color: #02a8c8;
        color: #fff;
    }
    
    .btn-warning {
        background: #ffab00;
        border-color: #ffab00;
        color: #fff;
    }
    
    .btn-warning:hover {
        background: #e69a00;
        border-color: #e69a00;
        color: #fff;
    }
    
    .btn-danger {
        background: #ff3e1d;
        border-color: #ff3e1d;
        color: #fff;
    }
    
    .btn-danger:hover {
        background: #e63617;
        border-color: #e63617;
        color: #fff;
    }
    
    /* 分页样式 */
    .pagination {
        margin: 1rem 0 0 0;
        justify-content: center;
    }
    
    .pagination .page-link {
        padding: 0.5rem 0.75rem;
        color: #566a7f;
        background-color: #fff;
        border: 1px solid #d9dee3;
        margin: 0 0.2rem;
        border-radius: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .pagination .page-item.active .page-link {
        background-color: #696cff;
        border-color: #696cff;
        color: #fff;
    }
    
    .pagination .page-link:hover {
        color: #696cff;
        background-color: #f5f5f9;
        border-color: #d9dee3;
        transform: translateY(-1px);
    }
    
    .pagination .page-item.disabled .page-link {
        color: #a3a4cc;
        pointer-events: none;
        background-color: #fff;
        border-color: #d9dee3;
    }
    
    /* 模态框样式 */
    .modal-content {
        border: none;
        border-radius: 1rem;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    }
    
    .modal-header {
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
    }
    
    .modal-title {
        color: #566a7f;
        font-weight: 600;
    }
    
    .modal-body {
        padding: 1.5rem;
    }
    
    .modal-footer {
        border-top: 1px solid rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
    }
    
    .form-label {
        color: #566a7f;
        font-weight: 500;
        margin-bottom: 0.5rem;
    }
    
    .form-control {
        border-radius: 0.5rem;
        border: 1px solid #d9dee3;
        padding: 0.5rem 1rem;
        transition: all 0.2s ease;
    }
    
    .form-control:focus {
        border-color: #696cff;
        box-shadow: 0 0 0 0.2rem rgba(105, 108, 255, 0.25);
    }
    
    /* 下拉菜单样式 */
    .dropdown-menu {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        padding: 0.5rem;
        min-width: 160px;
    }
    
    .dropdown-item {
        padding: 0.6rem 1rem;
        color: #697a8d;
        border-radius: 0.4rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .dropdown-item:hover {
        background: #f8f9fa;
        color: #566a7f;
    }
    
    .dropdown-item i {
        font-size: 1.1rem;
    }
    
    .dropdown-item.view {
        color: #03c3ec;
    }
    
    .dropdown-item.edit {
        color: #ffab00;
    }
    
    .dropdown-item.delete {
        color: #ff3e1d;
    }
    
    .dropdown-item.view:hover {
        background: rgba(3, 195, 236, 0.1);
    }
    
    .dropdown-item.edit:hover {
        background: rgba(255, 171, 0, 0.1);
    }
    
    .dropdown-item.delete:hover {
        background: rgba(255, 62, 29, 0.1);
    }
    
    .dropdown-toggle::after {
        display: none;
    }
    
    .action-btn {
        background: #f8f9fa;
        border: 1px solid #d9dee3;
        color: #697a8d;
        padding: 0.4rem 0.8rem;
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .action-btn:hover {
        background: #f5f5f9;
        border-color: #d9dee3;
        color: #566a7f;
    }
    
    .action-btn i {
        font-size: 1.1rem;
    }
    
    /* 图片预览样式 */
    .notice-image-preview {
        max-width: 200px;
        max-height: 200px;
        object-fit: contain;
        margin: 0.5rem 0;
        border-radius: 0.5rem;
    }
    
    .image-preview-container {
        display: flex;
        flex-wrap: wrap;
        gap: 1rem;
        margin-top: 1rem;
    }

    .image-preview-item {
        position: relative;
        width: 150px;
        height: 150px;
    }

    .image-preview-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 0.5rem;
    }

    .image-preview-item .delete-btn {
        position: absolute;
        top: -10px;
        right: -10px;
        width: 24px;
        height: 24px;
        background: #ff3e1d;
        border: none;
        border-radius: 50%;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .image-preview-item .delete-btn:hover {
        background: #e63617;
        transform: scale(1.1);
    }

    /* 确保确认弹窗显示在最上层 */
    .swal2-container {
        z-index: 9999 !important;
    }

    .swal2-popup {
        z-index: 10000 !important;
    }

    /* 确保模态框不会遮挡确认弹窗 */
    .modal {
        z-index: 1050;
    }

    .modal-backdrop {
        z-index: 1040;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- 公告列表卡片 -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">公告列表</h5>
            <button type="button" class="btn btn-primary" onclick="showAddNoticeModal()">
                <i class="bx bx-plus"></i> 添加公告
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>标题</th>
                            <th>内容</th>
                            <th>发布人</th>
                            <th>创建时间</th>
                            <th>更新时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="noticeTableBody">
                        <!-- 公告数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            <!-- 分页控件 -->
            <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination">
                    <!-- 分页按钮将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </div>

    <!-- 添加公告模态框 -->
    <div class="modal fade" id="addNoticeModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加公告</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addNoticeForm">
                        <div class="mb-3">
                            <label class="form-label" for="noticeTitle">标题</label>
                            <input type="text" class="form-control" id="noticeTitle" name="notice_title" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="noticeContent">内容</label>
                            <textarea class="form-control" id="noticeContent" name="notice_content" rows="4" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="noticeImages">图片</label>
                            <input type="file" class="form-control" id="noticeImages" name="images" accept="image/*" multiple>
                            <div id="imagePreviewContainer" class="image-preview-container"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addNotice()">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 查看公告详情模态框 -->
    <div class="modal fade" id="viewNoticeModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">公告详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">标题</label>
                        <p id="noticeDetailTitle" class="form-control-static"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">内容</label>
                        <p id="noticeDetailContent" class="form-control-static"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">发布人</label>
                        <p id="noticeDetailPublisher" class="form-control-static"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">创建时间</label>
                        <p id="noticeDetailCreateTime" class="form-control-static"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">更新时间</label>
                        <p id="noticeDetailUpdateTime" class="form-control-static"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">图片</label>
                        <div id="noticeDetailImages" class="image-preview-container"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑公告模态框 -->
    <div class="modal fade" id="editNoticeModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑公告</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editNoticeForm">
                        <input type="hidden" id="editNoticeId">
                        <div class="mb-3">
                            <label class="form-label" for="editNoticeTitle">标题</label>
                            <input type="text" class="form-control" id="editNoticeTitle" name="notice_title" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="editNoticeContent">内容</label>
                            <textarea class="form-control" id="editNoticeContent" name="notice_content" rows="4" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="editNoticeImages">添加图片</label>
                            <input type="file" class="form-control" id="editNoticeImages" name="images" accept="image/*" multiple>
                            <div id="editImagePreviewContainer" class="image-preview-container"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateNotice()">保存</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    // 全局变量
    let allNotices = []; // 存储所有公告数据
    let currentPage = 1; // 当前页码
    const itemsPerPage = 10; // 每页显示的数量

    // 页面加载完成后获取公告列表
    document.addEventListener('DOMContentLoaded', function() {
        getNoticeList();
    });

    // 获取公告列表
    function getNoticeList() {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get('/api/notice/get_notice_list/')
            .then(function(response) {
                if (response.data.code === 200) {
                    allNotices = response.data.data;
                    currentPage = 1; // 重置到第一页
                    renderNoticeTable();
                    renderPagination();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取公告列表失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 渲染公告表格
    function renderNoticeTable() {
        const tbody = document.getElementById('noticeTableBody');
        tbody.innerHTML = '';

        // 计算当前页的数据
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const currentPageNotices = allNotices.slice(startIndex, endIndex);

        currentPageNotices.forEach(notice => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${notice.notice_id}</td>
                <td>${notice.notice_title}</td>
                <td class="notice-content">${notice.notice_content || '-'}</td>
                <td>${notice.notice_publisher || '-'}</td>
                <td>${notice.create_time}</td>
                <td>${notice.update_time}</td>
                <td class="action-buttons">
                    <div class="dropdown">
                        <button class="action-btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bx bx-dots-vertical-rounded"></i>
                            <span>操作</span>
                        </button>
                        <ul class="dropdown-menu">
                            <li>
                                <a class="dropdown-item view" href="#" onclick="viewNotice('${notice.notice_id}')">
                                    <i class="bx bx-show"></i>
                                    <span>查看</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item edit" href="#" onclick="editNotice('${notice.notice_id}')">
                                    <i class="bx bx-edit"></i>
                                    <span>编辑</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item delete" href="#" onclick="deleteNotice('${notice.notice_id}')">
                                    <i class="bx bx-trash"></i>
                                    <span>删除</span>
                                </a>
                            </li>
                        </ul>
                    </div>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    // 渲染分页控件
    function renderPagination() {
        const pagination = document.getElementById('pagination');
        const totalPages = Math.ceil(allNotices.length / itemsPerPage);
        
        let paginationHTML = '';
        
        // 上一页按钮
        paginationHTML += `
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage - 1})" aria-label="Previous">
                    <i class="bx bx-chevron-left"></i>
                </a>
            </li>
        `;

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            paginationHTML += `
                <li class="page-item ${currentPage === i ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                </li>
            `;
        }

        // 下一页按钮
        paginationHTML += `
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage + 1})" aria-label="Next">
                    <i class="bx bx-chevron-right"></i>
                </a>
            </li>
        `;

        pagination.innerHTML = paginationHTML;
    }

    // 切换页码
    function changePage(page) {
        if (page < 1 || page > Math.ceil(allNotices.length / itemsPerPage)) {
            return;
        }
        currentPage = page;
        renderNoticeTable();
        renderPagination();
    }

    // 显示添加公告模态框
    function showAddNoticeModal() {
        const modal = new bootstrap.Modal(document.getElementById('addNoticeModal'));
        document.getElementById('addNoticeForm').reset();
        document.getElementById('imagePreviewContainer').innerHTML = '';
        modal.show();
    }

    // 添加公告
    function addNotice() {
        const form = document.getElementById('addNoticeForm');
        const formData = new FormData(form);
        const imageFiles = document.getElementById('noticeImages').files;
        
        // 添加notice_publisher字段
        formData.append('notice_publisher', '{{request.session.user.id}}');

        // 立即关闭添加公告模态框
        const addNoticeModal = bootstrap.Modal.getInstance(document.getElementById('addNoticeModal'));
        addNoticeModal.hide();

        const loadingToast = Swal.fire({
            title: '添加中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        // 创建公告
        axios.post('/api/notice/create_notice/', formData)
            .then(function(response) {
                if (response.data.code === 200) {
                    const noticeId = response.data.data.notice_id;
                    
                    // 如果有图片，立即上传
                    if (imageFiles.length > 0) {
                        // 创建一个Promise数组来存储所有图片上传的Promise
                        const uploadPromises = Array.from(imageFiles).map(file => {
                            const imageFormData = new FormData();
                            imageFormData.append('image', file);
                            
                            return axios.post(`/api/notice/upload_notice_image/${noticeId}/`, imageFormData)
                                .catch(error => {
                                    console.error('图片上传失败:', error);
                                    return null; // 返回null而不是抛出错误，这样其他图片仍然可以继续上传
                                });
                        });

                        // 等待所有图片上传完成
                        return Promise.all(uploadPromises)
                            .then(() => {
                                return { success: true, noticeId };
                            });
                    } else {
                        return { success: true, noticeId };
                    }
                } else {
                    throw new Error(response.data.msg);
                }
            })
            .then(function(result) {
                if (result.success) {
                    Swal.fire({
                        icon: 'success',
                        title: '成功',
                        text: '公告添加成功',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        getNoticeList();
                    });
                }
            })
            .catch(function(error) {
                Swal.fire('错误', error.message || '添加公告失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 查看公告详情
    function viewNotice(noticeId) {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get(`/api/notice/get_notice/${noticeId}/`)
            .then(function(response) {
                if (response.data.code === 200) {
                    const notice = response.data.data;
                    document.getElementById('noticeDetailTitle').textContent = notice.notice_title;
                    document.getElementById('noticeDetailContent').textContent = notice.notice_content || '-';
                    document.getElementById('noticeDetailPublisher').textContent = notice.notice_publisher || '-';
                    document.getElementById('noticeDetailCreateTime').textContent = notice.create_time;
                    document.getElementById('noticeDetailUpdateTime').textContent = notice.update_time;

                    // 显示图片
                    const imageContainer = document.getElementById('noticeDetailImages');
                    imageContainer.innerHTML = '';
                    if (notice.notice_image && notice.notice_image.length > 0) {
                        notice.notice_image.forEach(image => {
                            const imageItem = document.createElement('div');
                            imageItem.className = 'image-preview-item';
                            imageItem.innerHTML = `
                                <img src="${image.image}" alt="公告图片">
                                <button type="button" class="delete-btn" onclick="deleteNoticeImage('${noticeId}', ${image.id})">
                                    <i class="bx bx-x"></i>
                                </button>
                            `;
                            imageContainer.appendChild(imageItem);
                        });
                    } else {
                        imageContainer.innerHTML = '<p>暂无图片</p>';
                    }

                    const modal = new bootstrap.Modal(document.getElementById('viewNoticeModal'));
                    modal.show();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取公告详情失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 删除公告
    function deleteNotice(noticeId) {
        Swal.fire({
            title: '确认删除',
            text: '确定要删除这个公告吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({
                    title: '删除中...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                axios.delete(`/api/notice/delete_notice/${noticeId}/`)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            Swal.fire({
                                icon: 'success',
                                title: '成功',
                                text: '公告删除成功',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                getNoticeList();
                            });
                        } else {
                            Swal.fire('错误', response.data.msg, 'error');
                        }
                    })
                    .catch(function(error) {
                        Swal.fire('错误', '删除公告失败', 'error');
                    })
                    .finally(function() {
                        loadingToast.close();
                    });
            }
        });
    }

    // 编辑公告
    function editNotice(noticeId) {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get(`/api/notice/get_notice/${noticeId}/`)
            .then(function(response) {
                if (response.data.code === 200) {
                    const notice = response.data.data;
                    document.getElementById('editNoticeId').value = notice.notice_id;
                    document.getElementById('editNoticeTitle').value = notice.notice_title;
                    document.getElementById('editNoticeContent').value = notice.notice_content || '';

                    // 显示现有图片
                    const imageContainer = document.getElementById('editImagePreviewContainer');
                    imageContainer.innerHTML = '';
                    if (notice.notice_image && notice.notice_image.length > 0) {
                        notice.notice_image.forEach(image => {
                            const imageItem = document.createElement('div');
                            imageItem.className = 'image-preview-item';
                            imageItem.innerHTML = `
                                <img src="${image.image}" alt="公告图片">
                                <button type="button" class="delete-btn" onclick="deleteNoticeImage('${noticeId}', ${image.id})">
                                    <i class="bx bx-x"></i>
                                </button>
                            `;
                            imageContainer.appendChild(imageItem);
                        });
                    }

                    const modal = new bootstrap.Modal(document.getElementById('editNoticeModal'));
                    modal.show();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取公告信息失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 更新公告
    function updateNotice() {
        const form = document.getElementById('editNoticeForm');
        const formData = new FormData(form);
        const noticeId = document.getElementById('editNoticeId').value;
        const imageFiles = document.getElementById('editNoticeImages').files;

        // 立即关闭编辑公告模态框
        const editNoticeModal = bootstrap.Modal.getInstance(document.getElementById('editNoticeModal'));
        editNoticeModal.hide();

        const loadingToast = Swal.fire({
            title: '保存中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        // 更新公告
        axios.post(`/api/notice/update_notice/${noticeId}/`, formData)
            .then(function(response) {
                if (response.data.code === 200) {
                    // 如果有新选择的图片，立即上传
                    if (imageFiles.length > 0) {
                        // 创建一个Promise数组来存储所有图片上传的Promise
                        const uploadPromises = Array.from(imageFiles).map(file => {
                            const imageFormData = new FormData();
                            imageFormData.append('image', file);
                            
                            return axios.post(`/api/notice/upload_notice_image/${noticeId}/`, imageFormData)
                                .catch(error => {
                                    console.error('图片上传失败:', error);
                                    return null; // 返回null而不是抛出错误，这样其他图片仍然可以继续上传
                                });
                        });

                        // 等待所有图片上传完成
                        return Promise.all(uploadPromises)
                            .then(() => {
                                return { success: true };
                            });
                    } else {
                        return { success: true };
                    }
                } else {
                    throw new Error(response.data.msg);
                }
            })
            .then(function(result) {
                if (result.success) {
                    Swal.fire({
                        icon: 'success',
                        title: '成功',
                        text: '公告信息更新成功',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        getNoticeList();
                    });
                }
            })
            .catch(function(error) {
                Swal.fire('错误', error.message || '更新公告信息失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 图片预览功能
    document.getElementById('noticeImages').addEventListener('change', function(e) {
        const container = document.getElementById('imagePreviewContainer');
        container.innerHTML = '';
        
        Array.from(e.target.files).forEach(file => {
            const reader = new FileReader();
            reader.onload = function(e) {
                const img = document.createElement('img');
                img.src = e.target.result;
                img.className = 'notice-image-preview';
                container.appendChild(img);
            }
            reader.readAsDataURL(file);
        });
    });

    document.getElementById('editNoticeImages').addEventListener('change', function(e) {
        const container = document.getElementById('editImagePreviewContainer');
        
        Array.from(e.target.files).forEach(file => {
            const reader = new FileReader();
            reader.onload = function(e) {
                const img = document.createElement('img');
                img.src = e.target.result;
                img.className = 'notice-image-preview';
                container.appendChild(img);
            }
            reader.readAsDataURL(file);
        });
    });

    // 删除公告图片
    function deleteNoticeImage(noticeId, imageId) {
        Swal.fire({
            title: '确认删除',
            text: '确定要删除这张图片吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({
                    title: '删除中...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                axios.delete(`/api/notice/delete_notice_image/${imageId}/`)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            // 先关闭当前模态框
                            const editModal = document.getElementById('editNoticeModal');
                            const viewModal = document.getElementById('viewNoticeModal');
                            if (editModal.classList.contains('show')) {
                                bootstrap.Modal.getInstance(editModal).hide();
                            }
                            if (viewModal.classList.contains('show')) {
                                bootstrap.Modal.getInstance(viewModal).hide();
                            }

                            Swal.fire({
                                icon: 'success',
                                title: '成功',
                                text: '图片删除成功',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                // 重新加载公告信息
                                if (editModal.classList.contains('show')) {
                                    editNotice(noticeId);
                                } else {
                                    viewNotice(noticeId);
                                }
                            });
                        } else {
                            Swal.fire('错误', response.data.msg, 'error');
                        }
                    })
                    .catch(function(error) {
                        Swal.fire('错误', '删除图片失败', 'error');
                    })
                    .finally(function() {
                        loadingToast.close();
                    });
            }
        });
    }
</script>
{% endblock %}

{% block nav_left %}
{% include "pc/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% include 'pc/公共样式配置/JS总样式.html' %}

{% block footer %}
    {% include "pc/components/Footer.html" %}
{% endblock %}